package jpsProject1;

import java.awt.BorderLayout;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import java.util.Date;
import java.util.Properties;

/**
 * 
 * @author s0ereN
 * 
 */
@SuppressWarnings("serial")
public class View extends JPanel {

    private JTextArea status = new JTextArea();
    private File wFolder; // workingFolder
    // private File wFolder2; //workingFolderWithCopies
    private File fFolder; // finishedFolder
    private File oFolder; // outputFolder
    private File bFolder; // backupFolder
    private Properties p = new Properties();
    private File settings;

    private String batch;

    View() {
        buildView();
    }

    private void buildView() {
        JTextArea info = new JTextArea(
                "This program automaticly calls the batch with the images from the workfolder.\nIf the image has been processed, the raw image will be copied to backup folder and moved from work folder to finished folder.\nThe output folder must be specified to the folder where the batch-script drops the processed images.\n\n\nProgram written for JPS by SR v 0.9\n\n\n\n\n");
        status.setRows(20);
        status.setColumns(50);
        status.setEditable(false);
        info.setEditable(false);
        this.setLayout(new BorderLayout());
        this.add(info, BorderLayout.NORTH);
        this.add(new JScrollPane(status), BorderLayout.SOUTH);
    }

    public int startView() {
        if (JOptionPane.showConfirmDialog(null, "Want to load settings from file?") == 0) {
            boolean settingsLoaded = false;
            if (!loadSettings(null)) {
                settings = selectRoot("Couldn't find settings file. Please select one.", false, false);
                if (loadSettings(settings)) {
                    status.append("Settings loaded...\n");
                    settingsLoaded = true;
                }
            }else {
                settingsLoaded = true;
                status.append("Loaded settings:\n");
            }
            if (settingsLoaded) {
                wFolder = new File(p.getProperty("workingFolder"));
                status.append("wFolder = " + wFolder.toString() + "\n");
                bFolder = new File(p.getProperty("backupFolder"));
                status.append("bFolder = " + bFolder.toString() + "\n");
                oFolder = new File(p.getProperty("outputFolder"));
                status.append("oFolder = " + oFolder.toString() + "\n");
                fFolder = new File(p.getProperty("finishingFolder"));
                status.append("fFolder = " + fFolder.toString() + "\n");
                batch = p.getProperty("batch");
                status.append("batch = " + batch + "\n\n");
                checkPathes();
            }else {
                checkPathes();
            }
        }else {
            checkPathes();
        }
        return 1;
    }

    private void updateProperties() {
        try {
            if(settings == null){
                settings = new File("./settings.properties");
                settings.createNewFile();
            }
            if (settings.delete()) {
                BufferedWriter out = new BufferedWriter(new FileWriter(settings, true));
                
                out.write("##########################################################\n");
                out.write("# Settings file for JPS Imageprocessor\n");
                out.write("# Modified date: " + new Date(System.currentTimeMillis()) + "\n");
                out.write("##########################################################\n\n");
                out.write("workingFolder:" + buildPropertiesString(wFolder));
                out.write("\n");
                out.write("backupFolder:" + buildPropertiesString(bFolder));
                out.write("\n");
                out.write("outputFolder:" + buildPropertiesString(oFolder));
                out.write("\n");
                out.write("finishingFolder:" + buildPropertiesString(fFolder));
                out.write("\n");
                out.write("batch:" + buildPropertiesString(new File(batch)));
                out.write("\n");
                out.write("##########################################################");
                out.close();
                status.append("Settings updated.\n\n");
            }else {
                status.append("Couldn't delete settings file!\n");
            }
        }catch (IOException e) {
            status.append(e.getMessage());
            // e.printStackTrace();
        }
    }

    private String buildPropertiesString(File f) {
        char[] c = f.toString().toCharArray();
        String complete = "";
        for (int i = 0; i < c.length; i++) {
            complete += c[i];
            if (c[i] == '\\') {
                complete += "\\";
            }
        }
        return complete;
    }

    private void checkPathes() {
        boolean changed = false;
        if (wFolder == null || !wFolder.exists()) {
            wFolder = selectRoot("Select Eye-Fi output folder", true, true);
            status.append("Eye-Fi output folder set to:   " + wFolder + "\n");
            changed = true;
        }
        if (bFolder == null || !bFolder.exists()) {
            bFolder = selectRoot("Select folder where to backup raw images", true, true);
            status.append("Backup folder set to:   " + bFolder + "\n");
            changed = true;
        }
        if (oFolder == null || !oFolder.exists()) {
            oFolder = selectRoot("Select folder to save new processed images to", true, true);
            status.append("Output folder set to:    " + oFolder + "\n");
            changed = true;
        }
        if (fFolder == null || !fFolder.exists()) {
            fFolder = selectRoot("Select folder where to move processed raw images to", true, true);
            status.append("Finishing folder set to: " + fFolder + "\n");
            changed = true;
        }
        if (batch == null || !new File(batch).exists()) {
            batch = selectRoot("Select photoshop droplet", false, true).toString();
            status.append("Batch file from:         " + batch + "\n");
            changed = true;
        }
        if (changed) {
            if (JOptionPane.showConfirmDialog(null, "Want to save changed settings to file?") == 0) {
                updateProperties();
            }
        }
    }

    private boolean loadSettings(File settings) {
        BufferedInputStream stream = null;
        try {
            if (settings == null) {
                status.append("Trying to load default settings file.\n");
                stream = new BufferedInputStream(new FileInputStream("./settings.properties"));
            }else {
                stream = new BufferedInputStream(new FileInputStream(settings));
            }
        }catch (FileNotFoundException e1) {
            status.append(e1.getMessage() + "\n");
            // e1.printStackTrace();
            return false;
        }
        try {
            p.load(stream);
            stream.close();
        }catch (IOException e) {
            status.append(e.getMessage() + "\n");
            // e.printStackTrace();
            return false;
        }

        return true;
    }

    private File selectRoot(String message, boolean dir, boolean enableAbort) {
        JOptionPane.showMessageDialog(null, message);
        JFileChooser jfc = new JFileChooser(".");
        if (dir) {
            jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        }else {
            // FileNameExtensionFilter exFilter;
            // exFilter = new FileNameExtensionFilter("APP", "app"); // mac batchendung
            // jfc.setFileFilter(exFilter);
            jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        }
        int rc = jfc.showOpenDialog(null);
        if (rc == JFileChooser.APPROVE_OPTION) {
            // status.append(jfc.getSelectedFile().getName() + " successful selected.\n");
        }else if (enableAbort) {
            status.append("Selection abort. Exiting program.");
            for (int i = 0; i < 3; i++) {
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
                status.append(".");
            }
            System.exit(0); // Shutdown
        }else {
            return null;
        }
        return new File(jfc.getSelectedFile().getAbsolutePath());
    }// selectRoot

    public void appendToTextArea(String s) {
        status.append(s);
        status.setCaretPosition(status.getDocument().getLength());
    }

    public JTextArea getStatus() {
        return status;
    }

    public File getwFolder() {
        return wFolder;
    }

    public File getfFolder() {
        return fFolder;
    }

    public File getoFolder() {
        return oFolder;
    }

    public File getbFolder() {
        return bFolder;
    }

    public String getBatch() {
        return batch;
    }
}
